package org.jeecg.modules.business.controller;

import java.io.UnsupportedEncodingException;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.*;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jeecg.modules.business.entity.*;
import org.jeecg.modules.business.service.*;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.vo.LoginUser;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.business.vo.ContractInformationPage;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 合同信息表
 * @Author: jeecg-boot
 * @Date:   2020-12-03
 * @Version: V1.0
 */
@Api(tags="合同信息表")
@RestController
@RequestMapping("/business/contractInformation")
@Slf4j
public class ContractInformationController {
	@Autowired
	private IContractInformationService contractInformationService;
	@Autowired
	private IDeliveryDetailService deliveryDetailService;
	@Autowired
	private IWorkDetailsService workDetailsService;
	@Autowired
	private IPaymentDetailsService paymentDetailsService;
	@Autowired
	private IAuditOpinionService auditOpinionService;


	
	/**
	 * 分页列表查询
	 *
	 * @param contractInformation
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	@AutoLog(value = "合同信息表-分页列表查询")
	@ApiOperation(value="合同信息表-分页列表查询", notes="合同信息表-分页列表查询")
	@GetMapping(value = "/list")
	public Result<?> queryPageList(ContractInformation contractInformation,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ContractInformation> queryWrapper = QueryGenerator.initQueryWrapper(contractInformation, req.getParameterMap());
		Page<ContractInformation> page = new Page<ContractInformation>(pageNo, pageSize);
		IPage<ContractInformation> pageList = contractInformationService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param contractInformationPage
	 * @return
	 */
	@AutoLog(value = "合同信息表-添加")
	@ApiOperation(value="合同信息表-添加", notes="合同信息表-添加")
	@PostMapping(value = "/add")
	public Result<?> add(@RequestBody ContractInformationPage contractInformationPage) {
		ContractInformation contractInformation = new ContractInformation();
		BeanUtils.copyProperties(contractInformationPage, contractInformation);
		contractInformationService.saveMain(contractInformation, contractInformationPage.getDeliveryDetailList(),contractInformationPage.getWorkDetailsList(),contractInformationPage.getPaymentDetailsList());
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param contractInformationPage
	 * @return
	 */
	@AutoLog(value = "合同信息表-编辑")
	@ApiOperation(value="合同信息表-编辑", notes="合同信息表-编辑")
	@PutMapping(value = "/edit")
	public Result<?> edit(@RequestBody ContractInformationPage contractInformationPage) {
		ContractInformation contractInformation = new ContractInformation();
		BeanUtils.copyProperties(contractInformationPage, contractInformation);
		ContractInformation contractInformationEntity = contractInformationService.getById(contractInformation.getId());
		if(contractInformationEntity==null) {
			return Result.error("未找到对应数据");
		}
		contractInformationService.updateMain(contractInformation, contractInformationPage.getDeliveryDetailList(),contractInformationPage.getWorkDetailsList(),contractInformationPage.getPaymentDetailsList());
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合同信息表-通过id删除")
	@ApiOperation(value="合同信息表-通过id删除", notes="合同信息表-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<?> delete(@RequestParam(name="id",required=true) String id) {
		contractInformationService.delMain(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "合同信息表-批量删除")
	@ApiOperation(value="合同信息表-批量删除", notes="合同信息表-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<?> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.contractInformationService.delBatchMain(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功！");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "合同信息表-通过id查询")
	@ApiOperation(value="合同信息表-通过id查询", notes="合同信息表-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<?> queryById(@RequestParam(name="id",required=true) String id) {
		ContractInformation contractInformation = contractInformationService.getById(id);
		if(contractInformation==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(contractInformation);

	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "按时供货计划明细通过主表ID查询")
	@ApiOperation(value="按时供货计划明细主表ID查询", notes="按时供货计划明细-通主表ID查询")
	@GetMapping(value = "/queryDeliveryDetailByMainId")
	public Result<?> queryDeliveryDetailListByMainId(@RequestParam(name="id",required=true) String id) {
		List<DeliveryDetail> deliveryDetailList = deliveryDetailService.selectByMainId(id);
		return Result.OK(deliveryDetailList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "按计划完成工作明细通过主表ID查询")
	@ApiOperation(value="按计划完成工作明细主表ID查询", notes="按计划完成工作明细-通主表ID查询")
	@GetMapping(value = "/queryWorkDetailsByMainId")
	public Result<?> queryWorkDetailsListByMainId(@RequestParam(name="id",required=true) String id) {
		List<WorkDetails> workDetailsList = workDetailsService.selectByMainId(id);
		return Result.OK(workDetailsList);
	}
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "按计划完成支付明细通过主表ID查询")
	@ApiOperation(value="按计划完成支付明细主表ID查询", notes="按计划完成支付明细-通主表ID查询")
	@GetMapping(value = "/queryPaymentDetailsByMainId")
	public Result<?> queryPaymentDetailsListByMainId(@RequestParam(name="id",required=true) String id) {
		List<PaymentDetails> paymentDetailsList = paymentDetailsService.selectByMainId(id);
		return Result.OK(paymentDetailsList);
	}


    /**
    * 导出excel
    *
    * @param request
    * @param contractInformation
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ContractInformation contractInformation) {
      // Step.1 组装查询条件查询数据
      QueryWrapper<ContractInformation> queryWrapper = QueryGenerator.initQueryWrapper(contractInformation, request.getParameterMap());
      LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

      //Step.2 获取导出数据
      List<ContractInformation> queryList = contractInformationService.list(queryWrapper);
      // 过滤选中数据
      String selections = request.getParameter("selections");
      List<ContractInformation> contractInformationList = new ArrayList<ContractInformation>();
      if(oConvertUtils.isEmpty(selections)) {
          contractInformationList = queryList;
      }else {
          List<String> selectionList = Arrays.asList(selections.split(","));
          contractInformationList = queryList.stream().filter(item -> selectionList.contains(item.getId())).collect(Collectors.toList());
      }

      // Step.3 组装pageList
      List<ContractInformationPage> pageList = new ArrayList<ContractInformationPage>();
      for (ContractInformation main : contractInformationList) {
          ContractInformationPage vo = new ContractInformationPage();
          BeanUtils.copyProperties(main, vo);
          List<DeliveryDetail> deliveryDetailList = deliveryDetailService.selectByMainId(main.getId());
          vo.setDeliveryDetailList(deliveryDetailList);
          List<WorkDetails> workDetailsList = workDetailsService.selectByMainId(main.getId());
          vo.setWorkDetailsList(workDetailsList);
          List<PaymentDetails> paymentDetailsList = paymentDetailsService.selectByMainId(main.getId());
          vo.setPaymentDetailsList(paymentDetailsList);
          pageList.add(vo);
      }

      // Step.4 AutoPoi 导出Excel
      ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
      mv.addObject(NormalExcelConstants.FILE_NAME, "合同信息表列表");
      mv.addObject(NormalExcelConstants.CLASS, ContractInformationPage.class);
      mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("合同信息表数据", "导出人:"+sysUser.getRealname(), "合同信息表"));
      mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
      return mv;
    }

    /**
    * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
      MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
      Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
      for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
          MultipartFile file = entity.getValue();// 获取上传文件对象
          ImportParams params = new ImportParams();
          params.setTitleRows(2);
          params.setHeadRows(1);
          params.setNeedSave(true);
          try {
              List<ContractInformationPage> list = ExcelImportUtil.importExcel(file.getInputStream(), ContractInformationPage.class, params);
              for (ContractInformationPage page : list) {
                  ContractInformation po = new ContractInformation();
                  BeanUtils.copyProperties(page, po);
                  contractInformationService.saveMain(po, page.getDeliveryDetailList(),page.getWorkDetailsList(),page.getPaymentDetailsList());
              }
              return Result.OK("文件导入成功！数据行数:" + list.size());
          } catch (Exception e) {
              log.error(e.getMessage(),e);
              return Result.error("文件导入失败:"+e.getMessage());
          } finally {
              try {
                  file.getInputStream().close();
              } catch (IOException e) {
                  e.printStackTrace();
              }
          }
      }
      return Result.OK("文件导入失败！");
    }


	 /**
	  * 提交
	  *
	  * @param id
	  * @return
	  */

	 @GetMapping(value = "/submit")
	 public Result<?> submit(@RequestParam(name="id",required=true) String id) {

		 ContractInformation contractInformation = contractInformationService.getById(id);
		 if("1".equals(contractInformation.getReviewStatus())){
			 contractInformation.setReviewStatus("4");
			 contractInformationService.updateById(contractInformation);
			 return Result.OK("提交成功");
		 }else{
			 return  Result.error("提交失败");
		 }
	 }

	 /**
	  * 审核
	  */

	 @PostMapping(value = "/audit")
	 public Result<?> audit(@RequestParam(name="opinion",required=true) String opinion,@RequestParam(name="id",required=true) String id) {
		 LoginUser sysUser = (LoginUser)SecurityUtils.getSubject().getPrincipal();
	 	ContractInformation contractInformation = contractInformationService.getById(id);
		 AuditOpinion auditOpinion = new AuditOpinion();
		 if("4".equals(contractInformation.getReviewStatus())){
		 	auditOpinion.setOpinion(opinion);
		 	auditOpinion.setContractId(id);
		 	auditOpinion.setAuditTime(new Date());
		 	auditOpinion.setReviewer(sysUser.getRealname());
		 	contractInformation.setReviewStatus("2");
		 	contractInformationService.updateById(contractInformation);
		 	auditOpinionService.save(auditOpinion);
			 return Result.OK("审核成功");
		 }else{
			 return  Result.error("审核失败");
		 }
	 }

}
